<?php
// +----------------------------------------------------------------------
// | CleverPHP [ WE CAN DO IT JUST BeautySoft ]
// +----------------------------------------------------------------------
// | Copyright (c) 2012~2017 http://git.oschina.net/ceiba/CleverPHP All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: ceiba <ceiba_@126.com>
// +----------------------------------------------------------------------

class BaseModel {
	protected 	$db_name;
	private     $mongo=NULL;
	public  	$table_name="";
	public 		$Model="";
	public 		$Action="";
	private 	$fields=array();
	private 	$where=array();
	private 	$limit=array();
	public 		$is_write_log=true;
	public 		$is_last_update_time=FALSE;
	function __construct(){
		$this->_init();
	}
	function _init(){
		if (substr(PHP_VERSION, 0, 1) == '7') {
			//
		}
		Drive("DB/Mongodbs");
		if (!class_exists("mongodbs")){
			exit("is null Drive");
		}
		if (!$this->mongo){
			$mongodb_host=C("mongodb_host");
			if(!$mongodb_host && defined("MongoHost")){
				$mongodb_host=MongoHost;
			}
			if(!$mongodb_host){
				$mongodb_host="localhost:27017";
			}
			
			$mongodb_dbname=C("mongodb_dbname");
			if(!$mongodb_dbname && defined("MongoDbName")){
				$mongodb_host=MongoDbName;
			}
			if(!$mongodb_dbname){
				$mongodb_dbname="test";
			}
			
			
			$this->db_name=$mongodb_dbname;
			$this->mongo = new mongodbs($mongodb_host);
			$this->mongo->selectDb($this->db_name);
		}
	}
	//处理连惯性操作
	public function __call($method,$args) {
		if (strtolower($method)=="order" && is_array($args)){
			if (!is_array($args[0])){
				
				if (stripos($args[0],",")){
						$arrs=explode(",",$args[0]);
						$orders=array();
						foreach ($arrs as $k=>$v){
							$order_array=preg_split("/[\s]+/", $v);
							if (count($order_array)>1){
								$desc=1;
								if (strtolower($order_array[1])=="desc"){
									$desc=-1;
								}
								$orders["sort"][$order_array[0]]=$desc;
								
							}
							
						}
						$this->fields=$orders;
						
				}else{
					$order_array=preg_split("/[\s]+/", $args[0]);
					if (count($order_array)>1){
						$desc=1;
						if (strtolower($order_array[1])=="desc"){
							$desc=-1;
						}
						$orders["sort"][$order_array[0]]=$desc;
						$this->fields=$orders;
					}
					
				}
				
				
			}else{
				$this->fields["sort"]=$args[0];
			}
		}elseif (strtolower($method)=="where" && is_array($args)){
			$this->where=$args[0];
		}elseif (strtolower($method)=="limit" && is_array($args)){
			
			if (!is_array($args[0]) && !is_array($args[1])){
				$this->fields["skip"]=intval($args[0]);
				$this->fields["limit"]=intval($args[1]);
				
			}else{
				
				$this->limit=$args[0];
			}
		}
		return $this;
	}
	//查找多条数据
	public function select($query_condition=array(), $fields=array())
	{
		$this->_init();
		if (!empty($query_condition)){
			$this->where=$query_condition;
		}
		if (!empty($fields)){
			$this->fields=$fields;
		}
		$this->initTableName();
		
		$res=$this->mongo->find($this->table_name, $this->where,$this->fields);
		
		if ($res){
				foreach ($res as $k=>$v){
					if (isset($v["_id"])){
						if (is_array($v["_id"])){
							$res[$k]["_id"]=array_pop($v["_id"]);
						}
					}
					
					
				}
			}
		
		return $res;
	}
	
	//查找一条
	public function find($condition=array(), $fields=array())
	{
		$this->_init();
		
		if (!empty($query_condition)){
			$this->where=$query_condition;
		}
		if (!empty($fields)){
			$this->fields=$fields;
		}
		$this->initTableName();
		$res=$this->mongo->findOne($this->table_name, $this->where, $this->fields);
		
		return $res;
	}
	//统计
	public function count($condition=array())
	{
		
		$this->_init();
		if (!empty($condition)){
			$this->where=$condition;
		}
		$this->initTableName();
		$res=$this->mongo->count($this->table_name, $this->where);
		
		return $res;
	}
	
	//统计
	public function sum(string $sumField,array $condition=array())
	{
		if (empty($sumField)) return 0;
		$this->_init();
		if (!empty($condition)){
			$this->where=$condition;
		}
		$this->initTableName();
		$res=$this->mongo->sum($this->table_name, $sumField,$this->where);
		return $res;
	}
	//插入
	public function add($record){
		
		$this->_init();
		$this->initTableName();
		
		if (!array_key_exists("add_time", $record)){ $record["add_time"]=gmtime();}
		unset($record["navTabId"]);
		unset($record["rel"]);
		unset($record["callbackType"]);
		unset($record["forwardUrl"]);
		
		$res=$this->mongo->insert($this->table_name, $record);
		
		if ($res){
			return true;
		}
		$this->write_logs($this->mongo->error,0,2);
		return false;
	}
	//更新
	public function update($newdata,$condition=array(), $options=array("upsert"=>1))
	{
		$this->_init();
		$this->initTableName();
		$this->fields=array();
		if (!$this->find($condition)){
			return $this->add($newdata);
		}
		if (!empty($condition)){
			$this->where=$condition;
		}
		unset($newdata["navTabId"]);
		unset($newdata["rel"]);
		unset($newdata["callbackType"]);
		unset($newdata["forwardUrl"]);
		
		$res=0;
		if (!empty($this->where["_id"])){
			$res=$this->mongo->update($this->table_name, $this->where, $newdata, $options);
		}else{
			$resault=$this->select($this->where);
			if ($resault){
				foreach ($resault as $key=>$value){
					if (!empty($value["_id"])){
						
						$where["_id"]=newMongoId($value["_id"]);
						
						$res=$this->mongo->update($this->table_name, $where, $newdata, $options);
					}
				}
			}
		}
		if ($res){
			return true;
		}
		$this->write_logs($this->mongo->error,0,2);
		return false;
	}
	//删除数据
	function del($condition=array(), $options=array())
	{
		$this->_init();
		$this->initTableName();
		if (!empty($condition)){
			$this->where=$condition;
		}
		if (empty($this->where)){
			$this->where["_id"]=newMongoId($_REQUEST["id"]);
		}
		$res=$this->mongo->remove($this->table_name, $this->where, $options=array());
		if ($res){
			return true;
		}
		$this->write_logs($this->mongo->error,0,0);
		return false;
	}
	
	/**
	 * 写日志
	 * @param  $message 	日志内容
	 * @param  $tag			标志，1表示成功，0表示失败
	 * @param number $act	1表示插入 0表示删除 2表示更新
	 */
	public function write_logs($message,$tag=1,$act=1){
		return true;
		
	}
	
	//读日志
	public function read_logs($logs_id=""){
		
		
	}
	//修改表的指定属性值
	protected function update_filed_value($field,$value){
		$this->_init();
		$this->initTableName();
		$where["_id"]=newMongoId($_REQUEST["id"]);
		if (is_int($value)) {
			$data[$field]=intval($value);
		}else{
			$data[$field]="{$value}";
		}
		if ($this->is_last_update_time){
			$data["last_update_time"]=gmtime();
		}
		
		$res=$this->mongo->update($this->table_name, $where, $data);
		return $res;
	}
	
	public function getByid($sort="_id"){
		$this->_init();
		$this->initTableName();
		$res=$this->mongo->getByid($this->table_name,$sort,$this->where);
		return $res;
	}
	protected function initTableName(){
		return $this->table_name;
		$this->_init();
		$config=C();
		if (str_len(C("DB_PREFIX")) || $GLOBALS["prefix"]){
			$PREFIX=C("DB_PREFIX");
			if (!trim($PREFIX)){
				$PREFIX=$GLOBALS["prefix"];
			}
			if (str_len(trim($PREFIX))){
				if (!stripos("c".$this->table_name, $PREFIX)){
					$this->table_name=$PREFIX.$this->table_name;
				}
			}
			
		}
	}
	
}
?>